<!DOCTYPE html>
<html>
  <head><meta name="generator" content="Hexo 3.8.0">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="fengzhaoyang&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
  <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
    java反射基础 | fzy-blog
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/css/style.css">
  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
  <script src="/js/qrious.js"></script>
  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.png">
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>fzy-blog</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">Tags</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">Archives</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/project/" class="item-link">Projects</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">About</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">Tags</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">Archives</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/project/" class="menu-link">Projects</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">About</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>java反射基础</h2>
  <p class="post-date">2019-05-24</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">JAVA反射机制是在运行状态中，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意一个方法；这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。</span><br><span class="line"></span><br><span class="line"><span class="number">1</span>.通过一个对象获得完整的包名和类名 (注:所有类的对象其实都是Class的实例)</span><br><span class="line">Demo demo = <span class="keyword">new</span> Demo();</span><br><span class="line">demo.getClass().getName();</span><br><span class="line"><span class="number">2</span>.实例化Class类对象</span><br><span class="line"><span class="comment">//一般采用这种方式</span></span><br><span class="line">Class&lt;?&gt; demo1 = Class.forName(<span class="string">"Reflect.Demo"</span>); <span class="comment">//Reflect是包名 Demo是类名</span></span><br><span class="line">Class&lt;?&gt; demo2 = <span class="keyword">new</span> Demo().getClass();</span><br><span class="line">Class&lt;?&gt; demo3 = Demo.class;</span><br><span class="line"><span class="number">3</span>.通过Class实例化其他类的对象</span><br><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"Reflect.Person"</span>);</span><br><span class="line">Person per = (Person)clazz.newInstance();</span><br><span class="line"><span class="number">4</span>.通过Class调用其他类中的构造函数</span><br><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"Reflect.Person"</span>);</span><br><span class="line"><span class="comment">//取得全部的构造函数 包括父类的方法</span></span><br><span class="line">Constructor&lt;?&gt; cons[] = clazz.getConstructors();</span><br><span class="line">Person per1 = (Person)cons[<span class="number">0</span>].newInstance(<span class="string">"Rollen"</span>);</span><br><span class="line">Person per2 = (Person)cons[<span class="number">1</span>].newInstance(<span class="number">20</span>);</span><br><span class="line">Person per3 = (Person)cons[<span class="number">2</span>].newInstance(<span class="string">"Rollen"</span>,<span class="number">20</span>);</span><br><span class="line"><span class="number">5</span>.返回一个类实现的接口：</span><br><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"Reflect.Person"</span>);</span><br><span class="line"><span class="comment">//保存所有的接口</span></span><br><span class="line">Class&lt;?&gt; intes[] = clazz.getInterfaces();</span><br><span class="line">intes[<span class="number">0</span>].getName();</span><br><span class="line"><span class="number">6</span>.取得其他类中的父类</span><br><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"Reflect.Person"</span>);</span><br><span class="line"><span class="comment">//取得父类</span></span><br><span class="line">Class&lt;?&gt; temp = clazz.getSuperclass();</span><br><span class="line"><span class="number">7</span>.获得其他类中的全部构造函数</span><br><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"Reflect.Person"</span>);</span><br><span class="line">Constructor&lt;?&gt; cons[] = clazz.getConstructors();</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;cons.length;i++)&#123;</span><br><span class="line">    System.out.println(<span class="string">"构造方法："</span>+cons[i]);</span><br><span class="line">&#125;</span><br><span class="line"><span class="number">8</span>.取得本类的属性</span><br><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"Reflect.Person"</span>);</span><br><span class="line"></span><br><span class="line">Field[] field = clazz.getDeclaredFields();</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;field.length;i++)&#123;</span><br><span class="line">    <span class="keyword">int</span> mo = field[i].getModifiers();</span><br><span class="line">    String priv = Modifier.toString(mo);</span><br><span class="line">    Class&lt;?&gt; type = field[i].getType();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//获得所有类的方法包括父类的方法</span></span><br><span class="line">Field[] field1 = clazz.getFields();</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">0</span>;j&lt;freld1.length;j++)&#123;</span><br><span class="line">    <span class="keyword">int</span> mo = filed1[j].getModifiers();</span><br><span class="line">    String priv = Modifier.toString(mo);</span><br><span class="line">    Class&lt;?&gt; type = field1[i].getType();</span><br><span class="line">&#125;</span><br><span class="line"><span class="number">9</span>.调用类中的方法</span><br><span class="line"><span class="comment">//调用Person类中的sayChina方法</span></span><br><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"Reflect.Person"</span>);</span><br><span class="line">Method method = clazz.getMethod(<span class="string">"sayChina"</span>);</span><br><span class="line">method.invoke(clazz.newInstance());</span><br><span class="line"><span class="comment">//调用Person的sayHello方法</span></span><br><span class="line">method = clazz.getMethod(<span class="string">"sayHello"</span>,String.class);</span><br><span class="line">method.invoke(clazz.newInstance(),<span class="string">"Rollen"</span>,<span class="number">20</span>);</span><br></pre></td></tr></table></figure>
</section>
    <!-- Tags START -->
    
    <div class="tags">
      <span>Tags:</span>
      
  <a href="/tags#技术博文">
    <span class="tag-code">技术博文</span>
  </a>

    </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2019/05/24/技术博文/gitchat讲座PPT/">
        <span class="nav-arrow">← </span>
        
          gitchat 讲座 PPT
        
      </a>
    
    
      <a class="nav-right" href="/2019/05/24/技术博文/break的一个另类用法/">
        
          break的一个另类用法
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
    <div class="money-like">
      <div class="reward-btn">
        赏
        <span class="money-code">
          <span class="alipay-code">
            <div class="code-image"></div>
            <b>使用支付宝打赏</b>
          </span>
          <span class="wechat-code">
            <div class="code-image"></div>
            <b>使用微信打赏</b>
          </span>
        </span>
      </div>
      <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
    </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
    <div class="qrcode">
      <canvas id="share-qrcode"></canvas>
      <p class="notice">扫描二维码，分享此文章</p>
    </div>
    
    <!-- 二维码 END -->
    
    <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
  <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="nav">none</ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'https://fengzhaoy.github.io/2019/05/24/技术博文/java反射基础/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function () {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function () {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="' + src +
          '" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function () {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


<script>
  var qr = new QRious({
    element: document.getElementById('share-qrcode'),
    value: document.location.href
  });
</script>





    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2019
  </p>
</footer>

<script>
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async ("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function () {
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async ("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function () {
    $('figure pre').each(function (i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/js/script.js"></script>
  </body>
</html>